package com.azusa.ktc_manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    Environment environment;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //获取请求中的auth信息
        String auth = request.getHeader("auth");
        //解密前缀信息
        String prefix = environment.getProperty("jwt.config.prefix");
        if (StringUtils.isEmpty(auth)){
            requestContext.getResponse().setContentType("text/html;charset=UTF-8");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseBody("拒绝访问，无认证消息");
        }else{
            if (!StringUtils.isEmpty(prefix) && auth.startsWith(prefix)){
                //截取token
                String token = auth.substring(prefix.length());
                //解析token
                Claims claims = jwtUtil.parseJWT(token);
                if ("user".equals(claims.get("role"))){
                    Object jtl = claims.get("jti");
                    request.setAttribute("userId",jtl);//把登录用户放入请求体中
                }else {
                    requestContext.getResponse().setContentType("text/html;charset=UTF-8");
                    requestContext.setSendZuulResponse(false);
                    requestContext.setResponseBody("拒绝访问，无访问权限");
                }
            }else {
                requestContext.getResponse().setContentType("text/html;charset=UTF-8");
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseBody("拒绝访问，认证消息错误");
            }
        }
        return null;
    }
}
